package xin.marcher.wind.consistency.remote;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.marcher.wind.consistency.common.CommonRes;
import xin.marcher.wind.consistency.election.PeerElectionHandler;
import xin.marcher.wind.consistency.enums.PeerOpTypeEnum;
import xin.marcher.wind.consistency.remote.message.RegisterOrCancelRequest;
import xin.marcher.wind.consistency.remote.message.RegisterOrCancelResponse;
import xin.marcher.wind.consistency.sharding.ConsistencyTaskShardingContext;

import javax.annotation.Resource;

/**
 * 公用的请求对象
 *
 * @author marcher
 **/
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 选举和分片使用的处理器
     */
    @Resource
    private PeerElectionHandler peerElectionHandler;

    /**
     * 注册到 leader 节点
     *
     * @param registerOrCancelRequest 注册请求
     * @return 注册结果
     */
    @PostMapping("/registerOrCancel")
    public CommonRes<?> leaderHeartbeat(@RequestBody RegisterOrCancelRequest registerOrCancelRequest) {
        log.info("收到节点 [{}] 的请求 请求内容为:[{}]",
                PeerOpTypeEnum.ONLINE.getOpType().equals(registerOrCancelRequest.getOpType()) ? "上线" : "下线",
                JSONUtil.toJsonStr(registerOrCancelRequest));

        // 分片节点上下文
        ConsistencyTaskShardingContext consistencyTaskShardingContext = peerElectionHandler.getConsistencyTaskShardingContext();
        // 当前节点的id
        String currentPeerId = consistencyTaskShardingContext.getCurrentPeerId();
        // 当前leader的id
        String currentLeaderPeerId = consistencyTaskShardingContext.getCurrentLeaderPeerId();

        boolean isLeader = false;
        if (!StringUtils.isEmpty(currentLeaderPeerId) && !StringUtils.isEmpty(currentPeerId)) {
            isLeader = currentLeaderPeerId.equals(currentPeerId);
        }

        // 如果当前节点是leader节点
        RegisterOrCancelResponse registerResponse;
        if (isLeader) {
            registerResponse = RegisterOrCancelResponse.builder()
                    .leader(true)
                    .accessSuccess(true)
                    .replyPeerId(currentPeerId)
                    .registerOrCancelRequest(registerOrCancelRequest)
                    .build();
        } else {
            registerResponse = RegisterOrCancelResponse.builder()
                    .leader(false)
                    .accessSuccess(true)
                    .replyPeerId(currentPeerId)
                    .registerOrCancelRequest(registerOrCancelRequest)
                    .build();
        }
        peerElectionHandler.eventBus.post(registerResponse);
        return CommonRes.success(registerResponse);
    }
}
